
var validateTel1 = function(rule, value, callback){
    if (value === '') {
        callback(new Error('请输入手机号'));
    }
    //else if (!validateTel(value)) {
    //    callback(new Error('请输入正确的手机号'));
    //}
    else {
        callback();
    }
};

var validateTel2 = function(rule, value, callback){
    if (value === '') {
        callback(new Error('请输入手机号'));
    }
    //else if (!validateTel(value)) {
    //    callback(new Error('请输入正确的手机号'));
    //}
    else {
        callback();
    }
};

//修改密码--s

var checkTel = function(rule, value, callback){
    if (!value) {
        return callback(new Error('请输入手机号码'));
    }
    else if(!validateTel(value)){
        callback(new Error('请输入正确的手机号'));
    }else{
        callback();
    }
};
//var checkCode = function(rule, value, callback){
//    if (!value) {
//        return callback(new Error('请输入验证码'));
//    }
//    else if(!/^[0-9]+.?[0-9]*$/.test(value)){
//        callback(new Error('请输入数字值'));
//    }else{
//        callback();
//    }
//};
var validatePass3 = function(rule, value, callback){

    if (value === '') {
        callback(new Error('请输入密码'));
    }
    //else if(!validatePassWord(value)) {
    //    callback(new Error('8-20位登录密码，大小写字母+数字组合'));
    //}
    else {
        callback();
    }
};
var validatePass32 = function(rule, value, callback){
    if (value === '') {
        callback(new Error('请再次输入密码'));
    }
    else if (value !== document.getElementById('pass').value) {
        callback(new Error('两次输入的密码不一致'));
    } else {
        callback();
    }
};

//修改密码--e
new Vue({
    el: '#pc',
    data: {
        tabFlagTel: true,//默认手机号登陆
        getCodeFlag: true,
        againText: '',
        changePassword:false,
        //验证码登陆---ss
        ruleForm1: {
            tel: '',
            codeImg: '',
            num: '',
        },
        rules1: {
            tel: [
                {validator: validateTel1, trigger: 'blur'}
            ],
            codeImg:[
                { required: true, message: '请输入图形验证码', trigger: 'blur' },
            ],
            num: [
                { required: true, message: '请输入短信验证码', trigger: 'blur' },
            ],
        },
        //密码登陆---ss
        ruleForm2: {
            tel: '',
            pass: '',
        },
        rules2: {
            tel: [
                {validator: validateTel2, trigger: 'blur'}
            ],
            pass: [
                { required: true, message: '请输入密码', trigger: 'blur' },
            ],
        },
        //忘记密码---ss
        getCodeFlag3:true,
        againText3:'',
        ruleForm3: {
            tel:'',
            code:'',
            pass: '',
            checkPass: '',
        },
        rules3: {
            tel:[{ validator: checkTel, trigger: 'blur' }],
            code:[{ required: true, message: '请输入验证码', trigger: 'blur' },],
            pass: [
                { validator: validatePass3, trigger: 'blur' }
            ],
            checkPass: [
                { validator: validatePass32, trigger: 'blur' }
            ],
        },
        //图形验证码---ss
        txt:[], //验证码内容:
        codeImgFlagCheck:false,
        //密码状态图路径
        imgClose: '../images/close@3x.png',
        imgOpen: '../images/open@3x.png',
        imgEyeFlag: true,
        //获取验证码时返回的sessionid
        telCodeSessionid:null
    },
    created: function () {
    },
    mounted: function () {
        this.draw([])
    },
    methods: {
        //点击密码登陆或手机号验证码登陆按钮
        loginTelOrPassword:function(){
            var _this=this;
            var refDom=this.tabFlagTel?'ruleForm1':'ruleForm2';
            this.$refs[refDom].validate(function(valid) {
                if (valid) {
                    refDom=='ruleForm1'? _this.telLogin(_this.ruleForm1): _this.passWordLogin(_this.ruleForm2)
                } else {
                    console.log('error submit!');
                }
            });
        },
        //手机号登陆ajax
        telLogin:function(params){
            var _this=this;
            console.log('sessionid',_this.telCodeSessionid);
            _axios({
                url: '/api/login/adduser',
                method: 'post',
                data: {
                    phone:params.tel,
                    vcode:params.num,
                    sessionid:_this.telCodeSessionid
                },
            }).then(function (res) {
                var result=res.data;
                if(result.code=='200'){
                    //本地存储session
                    setSessionStorage('userInfo',{sessionid:result.sessionid,name:_this.ruleForm1.tel},true)
                    gotoUrl('首页')
                }else{
                    _this.$message({
                        message: result.message,
                        type: 'warning'
                    });
                }
            }).catch(function (err) {
                _this.$message({
                    message: err.message,
                    type: 'warning'
                });
            });
        },
        //密码登陆ajax
        passWordLogin:function(paramsData){
            var _this=this;
            _axios({
                url: '/api/login/pswdlog',
                method: 'post',
                data: {
                    phone:paramsData.tel,
                    password:paramsData.pass,
                },
            }).then(function (res) {
                var result=res.data;
                if(result.code=='200'){
                    //本地存储session
                    setSessionStorage('userInfo',{sessionid:result.sessionid,name:_this.ruleForm2.tel},true)
                    gotoUrl('首页')

                }else{
                    _this.$message({
                        message: result.message,
                        type: 'warning'
                    });
                }

            }).catch(function (err) {
                //_this.$message({
                //    message: err.message,
                //    type: 'warning'
                //});
            });
        },
        //修改密码按钮
        updatepwd:function(){
            var _this=this;
            this.$refs['ruleForm3'].validate(function(valid) {
                if (valid) {
                    _this.updataAjax(_this.ruleForm3)
                } else {
                    console.log('error submit!!');
                }
            });
        },
        updataAjax:function(paramsData){
            var _this=this;
            _axios({
                url: '/api/login/updatepwd',
                method: 'post',
                data: {
                    phone:paramsData.tel,
                    password:paramsData.pass,
                    code:paramsData.code,
                },
            }).then(function (res) {
                var result=res.data;
                if(result.code=='200'){
                    _this.$alert(result.message, '提示', {
                        confirmButtonText: '确定',
                        callback: action => {
                            _this.tabFlagTel=true;
                            _this.changePassword=false;
                            _this.$refs['ruleForm3'].resetFields();
                        }
                    });
                }else{
                    _this.$message({
                        message: result.message,
                        type: 'warning'
                    });
                }
            }).catch(function (err) {
                //_this.$message({
                //    message: err.message,
                //    type: 'warning'
                //});
            });
        },

        //手机登陆倒计时
        getNumCode:function(){
            var _this=this;
            this.$refs.ruleForm1.validateField('tel',function(tellError ){
                if(!tellError){
                    _this.$refs.ruleForm1.validateField('codeImg',function(codeImgError){
                        if(!codeImgError){
                            _this.checkCanvasCode()
                        }
                    })
                }
            });

        },
        //获取手机验证码ajax
        telCodeNum:function(){
            var _this=this;
            console.log('ruleForm1.tel--',_this.ruleForm1.tel);
            _axios({
                url: '/api/login/getvcode',
                method: 'post',
                data: {
                    phone:_this.ruleForm1.tel
                },
            }).then(function (res) {
                var result=res.data;
                if(result.code=='200'){
                    //接收sessionid
                    _this.telCodeSessionid=result.sessionid
                }else{
                    _this.$message({
                        message: result.message,
                        type: 'warning'
                    });
                }
            }).catch(function (err) {
                _this.$message({
                    message: err.message,
                    type: 'warning'
                });
            });
        },
        //修改密码倒计时
        getNumCode3:function(){
            this.$refs.ruleForm3.validateField('tel',function(tellError ){
                if(!tellError){
                    this.countDown('getCodeFlag3','againText3','setIntervalId3')
                }
            })

        },
        //倒计时封装
        countDown:function(flag,text,setIntervalId){
            var _this = this;
            this[flag] = false
            var time = 59;
            _this[text] = time + "s后重发"
            if(setIntervalId){
                clearInterval(setIntervalId)
            }
            setIntervalId = setInterval(function () {
                if (time <= 1) {
                    clearInterval(setIntervalId)
                    _this[flag] = true
                } else {
                    time--;
                    _this[text] = time + "s后重发"
                }
            }, 1000)
        },
        //切换图片验证
        canvasClick:function(){
            this.draw([]);
        },
        checkCanvasCode:function(){
            var val = this.ruleForm1.codeImg.toLowerCase();
            var num = this.txt.join("");   //用于把数组中的所有元素放入一个字符串。
            if(val == num){
                this.codeImgFlagCheck=false;
                //短信倒计时
                this.countDown('getCodeFlag','againText','setIntervalId1')
                //发送请求 获取手机短信验证码
                this.telCodeNum()
            }else{
               this.codeImgFlagCheck=true;
            }
        },
        draw(show_num) {
            var canvas_width = document.getElementById('canvas').offsetWidth;
            var canvas_height = document.getElementById('canvas').offsetHeight;
            var canvas = document.getElementById("canvas"); //获取到canvas的对象，演员
            var context = canvas.getContext("2d"); //获取到canvas画图的环境，演员表演的舞台
            canvas.width = canvas_width;
            canvas.height = canvas_height;
            var sCode ="a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
            var aCode = sCode.split(",");
            var aLength = aCode.length; //获取到数组的长度
            for (var i = 0; i < 4; i++) { //这里的for循环可以控制验证码位数（如果想显示6位数，4改成6即可）
                var j = Math.floor(Math.random() * aLength); //获取到随机的索引值
                // var deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
                var deg = Math.random() - 0.5; //产生一个随机弧度
                var txt = aCode[j]; //得到随机的一个内容
                show_num[i] = txt.toLowerCase();
                var x = 10 + i * 20; //文字在canvas上的x坐标
                var y = 20 + Math.random() * 8; //文字在canvas上的y坐标
                context.font = "bold 23px 微软雅黑";
                context.translate(x, y);
                context.rotate(deg);
                context.fillStyle = this.randomColor();
                context.fillText(txt, 0, 0);
                context.rotate(-deg);
                context.translate(-x, -y);
            }
            for (var i = 0; i <= 5; i++) { //验证码上显示线条
                context.strokeStyle = this.randomColor();
                context.beginPath();
                context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
                context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
                context.stroke();
            }
            for (var i = 0; i <= 30; i++) { //验证码上显示小点
                context.strokeStyle = this.randomColor();
                context.beginPath();
                var x = Math.random() * canvas_width;
                var y = Math.random() * canvas_height;
                context.moveTo(x, y);
                context.lineTo(x + 1, y + 1);
                context.stroke();
            }
            this.txt = show_num  //获取到随机的验证码
            console.log('ss',this.txt)
        },
        randomColor() {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            return "rgb(" + r + "," + g + "," + b + ")";
        },
        //切换密码的显示与隐藏状态
        switchOpenOrClose() {
            this.imgEyeFlag = !this.imgEyeFlag
        }

    }
})

